//
//  NewCreatEssay.m
//  shusheng
//
//  Created by rimi on 16/7/15.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "NewCreatEssay.h"
#import "NewEditorWord.h"
/**<  666*/
/**< plist */

/**< 打印路径 */
#define NSLOG_DOCUMENTS_PATH2  NSLog(@"%@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject);

/**< 沙盒地址 */
#define DOCUMENT_PATH2 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject
/**< 文件管理类 */
#define DEFAULT_FILEMANAGER2 [NSFileManager defaultManager]


@interface NewCreatEssay ()
@property (nonatomic,strong)NSString * plistOfEssay;
+ (void)updataDicOfNewObject:(NSMutableDictionary *)dicOfNewObject
                   txtString:(NSString *)txtString
                       index:(int)index;

@end


@implementation NewCreatEssay

//[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject];

- (int)creat:(NSString *)essayid
        essayname:(NSString *)essayname{
    _name = essayname;
    _essayid = essayid;
    
    return  [self haveDataId:essayid name:essayname];
    
}

//获取界面的数据信息
- (int)haveDataId:(NSString *)essayid
             name:(NSString*)name{
    
    if (essayid.length == 0 || name.length == 0) {//未命名
        NSLog(@"请输入完整~~");
//        [MBProgressHUD showError:@"请完整输入"];
        return 1;
        
    }else if ([self isExisting:essayid]){//防止相同名字存在
        NSLog(@"id重复~~");//yes~>名字相同，
//        [MBProgressHUD showError:@"id重复"];
        return 2;
        
    }else{
        //存储操作
        int result = [self save];
//        [MBProgressHUD showError:@"创建成功"];
        return result;
//        [self delet];
//        return 5;
    }
    
}
//遍历已有小说名
- (BOOL)isExisting:(NSString *)essayid{
    //调用查询
    //得到名字
    //对比
    
    NSArray *essays = [self read];//查看操作
    NSDictionary *dic = [NSDictionary dictionary];
    for (int i = 0; i < essays.count ; i++) {
        
        dic = essays[i];
        NSString *idStr = [dic objectForKey:@"essayId"];
        if ([essayid isEqualToString:idStr]) {
            NSLog(@"重名");
            return YES;
        }
    }
    NSLog(@"没重名");
    return NO;
}

//存储操作
- (int)save{
    
    //获取沙盒（plist）路径,拼接
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    
    //判断plist文件路径是否存在~如果存在，则根据plist文件路径初始化根数组（代表有数据，取出原有数据再存，才不会覆盖==获取原有的数据）；否则直接初始化根数组。
    NSMutableArray * rootArr = nil;
   
    if ([DEFAULT_FILEMANAGER2 fileExistsAtPath:path ]) {//文件管理机制arr
        rootArr=[NSMutableArray  arrayWithContentsOfFile:path];
    }else{
        rootArr =[@[]mutableCopy];
    }
    
    //打包用户信息
    
    NSString *wordTxt = [NSString stringWithFormat:@"essayId=%@->name=%@.txt",_essayid,_name];
   
//     [AVUser currentUser].objectId;
    NSDictionary * infoDict = @{@"userId":[AVUser currentUser].objectId,@"essayId":_essayid,@"name":_name,@"time":[ToolOfBasic nowTime],@"word":wordTxt,@"objectId":@""};
    NSLog(@"infoDict=%@",infoDict);
    //将用户信息存到根数组
    [rootArr insertObject:infoDict atIndex:0];
     NSLog(@"创建的plist路径");
    NSLOG_DOCUMENTS_PATH2;
    //(将根数组写入沙盒文件中)
    if ([rootArr writeToFile:path atomically:YES]) {
        NSLog(@"plist存储成功");
        NSLog(@"文章创建成功");

        //txt
        [NewEditorWord creatOneTxtFile:wordTxt];
       
        return 3;
        
    }else{
        NSLog(@"plist存储失败");
//        [MBProgressHUD showSuccess:@"创建失败"];
        return 5;
    }
    
  
    
}
//查询操作
+ (NSArray *)read{
    //路径
    
     NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *dataEssayOfOurs = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"没有数据。/(ㄒoㄒ)/~~");
    }else{
        for (int i = 0; i < datas.count; i ++) {
            if ([[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [dataEssayOfOurs addObject:datas[i]];
            }
        }
        NSLog(@"结果%@",dataEssayOfOurs);
    }
    return dataEssayOfOurs;
}
- (NSArray *)read{
    //路径
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *dataEssayOfOurs = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"没有数据。/(ㄒoㄒ)/~~");
    }else{
        for (int i = 0; i < datas.count; i ++) {
            if ([[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [dataEssayOfOurs addObject:datas[i]];
            }
        }
        NSLog(@"结果%@",dataEssayOfOurs);
    }
    return dataEssayOfOurs;
}

+ (BOOL)writeObjectId:(NSString *)objectId
            txtString:(NSString *)txtString
              essayId:(NSString *)essayId{
    BOOL yOrN = NO;
    
    //路径
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *dataEssayOfOurs = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"没有数据。/(ㄒoㄒ)/~~");
    }else{
        for (int i = 0; i < datas.count; i ++) {
            if ([[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [dataEssayOfOurs addObject:datas[i]];
            }
        }
        //得到自己的
        //找一个
        for (int j = 0; j <dataEssayOfOurs.count; j ++) {
            if ([essayId isEqualToString:dataEssayOfOurs[j][@"essayId"]]) {
                //找到
                //接收过来变成新的
                int index = j;
                NSDictionary *dicOfWillWrite = dataEssayOfOurs[j];
                NSMutableDictionary *dicOK = [NSMutableDictionary dictionaryWithDictionary:dicOfWillWrite];
                [dicOK setObject:objectId forKey:@"objectId"];
                
                //删除旧的
                [self deleteSourceOfEssayId:essayId];
                
                //把新的加入
                [self updataDicOfNewObject:dicOK txtString:txtString index:index];
                NSLog(@"旧的结果%@",dataEssayOfOurs[j]);
                yOrN = YES;
                break;
            }
        }

       
    }
    
    return yOrN;
}
+ (void)updataDicOfNewObject:(NSMutableDictionary *)dicOfNewObject
                   txtString:(NSString *)txtString
                       index:(int)index{
    //获取沙盒（plist）路径,拼接
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    
    //判断plist文件路径是否存在~如果存在，则根据plist文件路径初始化根数组（代表有数据，取出原有数据再存，才不会覆盖==获取原有的数据）；否则直接初始化根数组。
    NSMutableArray * rootArr = nil;
    
    if ([DEFAULT_FILEMANAGER2 fileExistsAtPath:path ]) {//文件管理机制arr
        rootArr=[NSMutableArray  arrayWithContentsOfFile:path];
    }else{
        rootArr =[@[]mutableCopy];
    }
    
    NSDictionary * infoDict = [NSDictionary dictionaryWithDictionary:dicOfNewObject];
    NSLog(@"infoDict=%@",infoDict);
    //将用户信息存到根数组
    [rootArr insertObject:infoDict atIndex:index];
    NSLog(@"创建的plist路径");
    //(将根数组写入沙盒文件中)
    if ([rootArr writeToFile:path atomically:YES]) {
        NSLog(@"plist存储成功");
        NSLog(@"文章创建成功");
        
        //txt更新文本内容
        [NewEditorWord writeToOneTxt:dicOfNewObject[@"essayName"] words:txtString];
        

        
    }else{
        NSLog(@"plist存储失败");
     
    }
    
    
    
}

+ (NSString *)readObjectIdOfEssayId:(NSString *)essayId{
    NSString *objectId = @"";
    //路径
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    //数据
    NSArray * datas = [NSArray arrayWithContentsOfFile:path];
    NSMutableArray *dataEssayOfOurs = [@[] mutableCopy];
    
    if (!datas || datas.count == 0) {
        NSLog(@"没有数据。/(ㄒoㄒ)/~~");
    }else{
        
        for (int i = 0; i < datas.count; i ++) {
            if ([[AVUser currentUser].objectId isEqualToString:datas[i][@"userId"]]) {
                [dataEssayOfOurs addObject:datas[i]];
            }
        }
        for (int j = 0; j < dataEssayOfOurs.count; j ++) {
            if ([essayId isEqualToString:dataEssayOfOurs[j][@"essayId"]]) {
                objectId = dataEssayOfOurs[j][@"objectId"];
            }
        }
        
       
    }
    return objectId;
}

//删除操作
//+ (NSArray *)deleteSourceOfIndexPathRow:(NSInteger)indexPathrow{
// 
//    NSString *path = [DOCUMENT_PATH2 stringByAppendingString:PlistOfEssay];
//    NSMutableArray *arr = [[NSMutableArray alloc]initWithContentsOfFile:path];//得到数组
//    
//    if (arr && arr.count > 0) {//从文件删除数组
//        //数据存在~移除数据
//        
//        //得到元素
//        //删元素
//        NSLog(@"indexPathrow%ld删除的源--%@",(long)indexPathrow,arr[indexPathrow]);
//        [arr removeObjectAtIndex:indexPathrow];
//        //从写入plist
//        NSArray *array = [NSArray arrayWithArray:arr];
//        [array writeToFile:path atomically:YES];
//        return array;
//        //数据不存在~无需操作数据
//    }else{
//        NSLog(@"plist为空，删除失败");
//        return NULL;
//    }
//    
//}


+ (NSArray *)deleteSourceOfEssayId:(NSString *)essayId{
    
    NSString *path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    NSMutableArray *arr = [[NSMutableArray alloc]initWithContentsOfFile:path];//得到数组
    NSMutableArray *arrOfOur = [@[]  mutableCopy];
    if (arr && arr.count > 0) {
        //从文件删除数组
        //数据存在~移除数据
        
        //得到元素
        //删元素
        for (int i = 0 ; i < arr.count; i ++) {
            if ([arr[i][@"userId"]isEqualToString:[AVUser currentUser].objectId]) {
                [arrOfOur addObject:arr[i]];
            }
        }

        for (int j = 0; j < arrOfOur.count; j ++) {
            if ([essayId isEqualToString:arrOfOur[j][@"essayId"]]) {
//                [arrOfOur removeObjectAtIndex:j];
                [arrOfOur removeObject:arrOfOur[j]];
//                NSLog(@"删掉%@",arrOfOur[j]);
            }
        }
         NSLog(@"删掉之后结果%@",arrOfOur);
        [arrOfOur writeToFile:path atomically:YES];
        //从写入plist
        NSArray *array = [NSArray arrayWithArray:arrOfOur];
        return array;
        //数据不存在~无需操作数据
    }else{
        NSLog(@"plist为空，删除失败");
        return NULL;
    }
    
}


//服务器获得数据进行存储
+ (void)networkSynchronizationArray:(NSArray *)arrOfNet{
    //获取沙盒（plist）路径,拼接
    NSString * path = [DOCUMENT_PATH2 stringByAppendingString:[NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId]];
    
    for (int i = 0;  i <arrOfNet.count ; i ++) {
        NSString *  essayid = [NSString stringWithFormat:@"%@",arrOfNet[i][@"essayID"]];
        NSString *  time = arrOfNet[i][@"time"];
        NSString *  name = arrOfNet[i][@"essayName"];
        NSString *  objectId = arrOfNet[i][@"objectId"];
        NSString *  wordString = arrOfNet[i][@"essayString"];
        
        if ([NewCreatEssay isExistingOfNetSaveEssayId:essayid]) {
               NSLog(@"本地已经存在");
        }else{
            //判断plist文件路径是否存在~如果存在，则根据plist文件路径初始化根数组（代表有数据，取出原有数据再存，才不会覆盖==获取原有的数据）；否则直接初始化根数组。
            NSMutableArray * rootArr = nil;
            
            if ([DEFAULT_FILEMANAGER2 fileExistsAtPath:path ]) {//文件管理机制arr
                rootArr=[NSMutableArray  arrayWithContentsOfFile:path];
            }else{
                rootArr =[@[]mutableCopy];
            }
            
            //打包用户信息
            
            NSString *wordTxt = [NSString stringWithFormat:@"essayId=%@->name=%@.txt",essayid,name];
            
            NSDictionary * infoDict = @{@"userId":[AVUser currentUser].objectId,@"essayId":essayid,@"name":name,@"time":time,@"word":wordTxt,@"objectId":objectId};
            NSLog(@"infoDict=%@",infoDict);
            //将用户信息存到根数组
            [rootArr insertObject:infoDict atIndex:0];
            NSLog(@"创建的plist路径");
            NSLOG_DOCUMENTS_PATH2;
            //(将根数组写入沙盒文件中)
            if ([rootArr writeToFile:path atomically:YES]) {
                NSLog(@"plist存储成功");
                NSLog(@"文章创建成功");
                
                //txt
                [NewEditorWord creatOneTxtFile:wordTxt];
                [NewEditorWord writeToOneTxt:wordTxt words:wordString];
            }
        }
        
    }
}


//遍历已有小说名
+ (BOOL)isExistingOfNetSaveEssayId:(NSString *)essayid{
    //调用查询
    //得到名字
    //对比
    
    NSArray *essays = [NewCreatEssay read];//查看操作
    NSDictionary *dic = [NSDictionary dictionary];
    for (int i = 0; i < essays.count ; i++) {
        
        dic = essays[i];
        NSString *idStr = [dic objectForKey:@"essayId"];
        if ([essayid isEqualToString:idStr]) {
            NSLog(@"重名");
            return YES;
        }
    }
    NSLog(@"没重名");
    return NO;
}

- (NSString *)plistOfEssay{
    if (!_plistOfEssay) {
        _plistOfEssay = [NSString stringWithFormat:@"%@UserEssaysArr.plist",[AVUser currentUser].objectId];
    }
    return _plistOfEssay;
}
@end
